/* 生成sign */

import { SIGN_SECRET as secretKey } from '@/config'

import { UUID } from 'uuid-js'
import md5 from 'md5'

function addSignToHeader(config) {
  const timestamp = new Date().getTime()
  const nonce = UUID.create().toString()

  // url 路径参数
  const urlParams = new URLSearchParams(config.url).toString().split('&')
  // config 上可能的 query 参数
  const query = new URLSearchParams(config.params).toString().split('&')
  let params = [].concat(urlParams, query)

  params = ['timestamp=' + timestamp, 'nonce=' + nonce, ...new Set(params)]
  params = params.sort((a, b) => (a + '').localeCompare(b + ''))
  params = params.join('').replace(/=/g, '') + secretKey
  let sign = md5(params).toUpperCase()
  config.headers = {
    ...config.headers,
    'X-Sign-Timestamp': timestamp,
    'X-Sign-Nonce': nonce,
    'X-Sign': sign
  }

  return config
}


export default addSignToHeader